<?php
/**
 * Created by JetBrains PhpStorm.
 * User: zhouyang
 * Date: 13-7-15
 * Time: 下午4:31
 * To change this template use File | Settings | File Templates.
 */
class RolesDB  extends DBReader{
    private $sql_param = 'role_id, role_name';

    //根据role_id 获取 role 信息
    public function get($role_id){

        $sql = 'select '.$this->sql_param.' from roles where role_id = :role_id';

        return $this->db()->getRow($sql,array('role_id'=>$role_id));
    }

    //获取角色信息列表<带分页>
    public function getRoleList($curr_page,$per_page,$filter = array()){
        $where = ' 1=1 ';
        $bindarr = array();

        if(isset($filter['role_name'])){
            $where .= ' and role_name like :role_name';
            $bindarr['role_name'] = '%'.$filter['role_name'].'%';
        }

        $ret = $this->pager($curr_page, $per_page)
            ->ct('select count(role_id) from roles where '.$where,$bindarr)
            ->rs('select '.$this->sql_param.' from roles where '.$where.' order by role_id desc', $bindarr);
        return $ret;
    }

    //获取所有角色信息
    public function getRoles($filter = array()){
        $where = ' 1=1 ';
        $bindarr = array();

        if(isset($filter['role_name'])){
            $where .= ' and role_name like :role_name';
            $bindarr['role_name'] = '%'.$filter['role_name'].'%';
        }

        $sql = 'select '.$this->sql_param.' from roles where '. $where .' order by role_id desc';

        return $this->db()->getAll($sql,$bindarr);
    }

    //添加角色信息
    public function addRole($role_name){

        $sql = "insert into roles(role_name) values(:role_name)";

        $bindarr = array(
            'role_name'=>$role_name,
        );
        $this->db()->execute($sql,$bindarr);
        return $this->db()->lastInsertId();
    }

    //删除角色信息
    public function delRole($role_id){

        $sql = "delete from roles where role_id = :role_id";

        $bindarr = array(
            'role_id'=>$role_id,
        );
        $rs = $this->db()->execute($sql,$bindarr);

        return $rs->rowCount();
    }

    //更新角色信息
    public function updateRole($role_id,$role_name){

        $bindarr = array(
            'role_name'=>$role_name,
            'role_id'=>$role_id,
        );
        $sql = "update roles set role_name = :role_name where role_id = :role_id";
        $rs = $this->db()->execute($sql,$bindarr);
        return $rs->rowCount();
    }

    //获取角色拥有的cate信息
    public function getCateRoles($cate_id){

        $sql = "select r.* from roles r left join cate_has_roles cr on r.role_id = cr.role_id where cr.cate_id = :cate_id";

        return $this->db()->getAll($sql,array('cate_id'=>$cate_id));
    }
}